<template>
  <view>
    <u-navbar leftText="返回" title="投诉建议添加页面" :autoBack="true" :placeholder="true"/>
    <view>
      <u-form labelPosition="left" :model="complaint">
        <u-form-item label="类型:" prop="complaintSuggestType">
          <u-radio-group v-model="complaint.complaintSuggestType" placement="row">
            <u-radio key='1' name='Complaint' :label="'Complaint'" value="Complaint">投诉</u-radio>
            <u-radio key='2' name='Suggest' :label="'Suggest'" value="Suggest">建议</u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="小区:" prop="communityId" @click="show = true">
          <u-picker :show="show" :columns="columns"
                    @confirm="handleConfirm"
                    @cancel="handleCancel"
                    keyName="label"
                    v-model="complaint.communityId"></u-picker>
          <u-input ref="selectBtn" v-model="inpText" placeholder="请选择要投诉或建议的小区"/>
        </u-form-item>
        <u-form-item label="内容:" prop="complaintSuggestContent">
          <u-textarea v-model="complaint.complaintSuggestContent" placeholder="请输入内容"/>
        </u-form-item>
        <u-form-item label="图片:" prop="complaintImgs">
          <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="complaintImgs"
                    multiple :maxCount="9" :previewFullImage="true"/>
        </u-form-item>
        <u-form-item class="ok-But">
          <div style="width: 500rpx; margin-left: 17%">
            <u-button type="primary" text="发表" @click="okAdd"/>
          </div>
        </u-form-item>
      </u-form>
    </view>
    <uni-toast id="toast"/> <!-- 添加uni-toast组件 -->
  </view>
</template>

<script>
export default {
  data() {
    return {
      complaint: {
        "complaintSuggestId": null,
        "communityId": "",
        "complaintSuggestType": "Complaint",
        "complaintSuggestContent": "",
        "createBy": "",
        "createTime": "",
        "updateBy": "",
        "updateTime": "",
        "remark": "",
        "complaintImgs": "",
        "userId": ""
      },
      fileList: [],
      show: false,
      columns: [],
      inpText: "",
      imgs: [],
    }
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1);
      console.log(this.fileList)
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this.fileList.length
      lists.map((item) => {
        this.fileList.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        console.log("上传返回：", result)
        let item = this.fileList[fileListLen]
        this.fileList.splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }));
        fileListLen++;
        console.log("fileListLen：", fileListLen);
      }
      console.log("图片容器：", this.fileList);
    },
    uploadFilePromise(url) {
      //插件方法
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: 'http://localhost:8080/uni-app/zyComplaintSuggest/sugUploadImages', // 仅为示例，非真实的接口地址
          filePath: url,
          name: 'file',
          success: (res) => {
            // setTimeout(() => {
            // 	resolve(res.data.data)
            // }, 1000)
            // 在 success 回调中应该先检查是否上传成功，再进行后续处理
            console.log(res)
            if (res.statusCode == 200) {
              const result = JSON.parse(res.data);
              resolve(result.data); // 假设后端返回的数据结构中有一个 data 字段表示上传后的 URL
            } else {
              reject(new Error("OSS上传失败"));
            }
          }
        });
      })
    },
    //发表按钮点击事件
    okAdd() {
      let complaintData = this.complaint; // 保存complaint对象到变量中
      let fileListData = this.fileList; // 保存fileList到变量中
      let that = this; // 保存this到变量that
      uni.showModal({
        title: '提示',
        content: '是否确定发表投诉/建议？（发表后无法修改）',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: function (res) {
          if (res.confirm) {
            //获取业主ID（先定义固定的，后从作用域取值）
            complaintData.userId = uni.getStorageSync('ownerId');
            //图片容器放到实体中
            for (var i = 0; i < fileListData.length; i++) {
              complaintData.complaintImgs += fileListData[i].url;
              if (i != fileListData.length - 1) {
                complaintData.complaintImgs += ",";
              }
            }
            console.log(complaintData);
            that.$http.post("/uni-app/zyComplaintSuggest/complaintAdd", complaintData)
                .then(res => {
                  uni.navigateBack({
                    delta: 1, // 返回上一层页面
                    success: function () {
                      // 刷新上一层页面
                      let pages = getCurrentPages();
                      let prevPage = pages[pages.length - 2];
                      prevPage.onShow(); // 执行上一层页面的onShow生命周期钩子函数
                    }
                  });
                }).catch(err => {
              console.log("失败" + err)
            })

            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    async selectComityAll() {
      let userId = uni.getStorageSync('ownerId');
      let res = await this.$http.get('/uni-app/zyComplaintSuggest/communitys/' + userId);
      let list = res.data.data;
      let arr = new Array();
      for (var i = 0; i < list.length; i++) {
        let key = {label: "", id: ""};
        key.label = list[i].communityName;
        key.id = list[i].communityId;
        this.$set(arr, i, key);
      }
      this.columns.push(arr);

      console.log(this.columns)
    },
    handleConfirm(value) {
      console.log('确定选择', value);
      this.inpText = value.value[0].label;
      this.complaint.communityId = value.value[0].id;
      console.log(this.inpText)
      this.show = false; // 关闭选择器
    },
    handleCancel() {
      // 处理取消按钮点击事件
      console.log('取消选择');
      this.show = false; // 关闭选择器
    },


  },
  mounted() {
    this.complaint = {
      "complaintSuggestId": null,
      "communityId": "",
      "complaintSuggestType": "Complaint",
      "complaintSuggestContent": "",
      "createBy": "",
      "createTime": "",
      "updateBy": "",
      "updateTime": "",
      "remark": "",
      "complaintImgs": "",
      "userId": ""
    };
    this.selectComityAll();
  }
}
</script>

<style>
.u-radio-group .u-radio {
  margin-right: 30px;
}
</style>
